<template>
  <div class="user-orders-container">
    <frontend-header/>

    <div class="container">
      <div class="page-header">
        <h1>我的订单</h1>
        <p>查看和管理您的所有订单</p>
      </div>

      <div class="content-wrapper">
        <!-- 侧边导航 -->
        <div class="sidebar">
          <div class="user-info-card">
            <div class="avatar-container">
              <img :src="userInfo.avatar" :alt="userInfo.name" class="user-avatar">
            </div>
            <h3>{{ userInfo.name || userInfo.username }}</h3>
            <p class="user-stats">共 {{ orders.length }} 个订单</p>
          </div>

          <el-menu
              :default-active="activeMenu"
              class="profile-menu"
              router
          >
            <el-menu-item index="/user/profile">
              <el-icon>
                <User/>
              </el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="/user/courses">
              <el-icon>
                <VideoPlay/>
              </el-icon>
              <span>我的课程</span>
            </el-menu-item>
            <el-menu-item index="/user/orders">
              <el-icon>
                <Document/>
              </el-icon>
              <span>我的订单</span>
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 主要内容 -->
        <div class="main-content">
          <div class="order-filters">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索订单号或课程名称"
                prefix-icon="Search"
                class="search-input"
            >
              <template #append>
                <el-button type="primary" @click="handleSearch">
                  <el-icon>
                    <Search/>
                  </el-icon>
                  搜索
                </el-button>
              </template>
            </el-input>
            <el-select v-model="filterStatus" placeholder="订单状态" class="filter-select">
              <el-option label="全部" value=""></el-option>
              <el-option label="未支付" value="0"></el-option>
              <el-option label="已支付" value="1"></el-option>
              <el-option label="已退款" value="2"></el-option>
            </el-select>
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                class="date-picker"
            />
          </div>
          <!--订单列表-->
          <el-table
              :data="orders"
              style="width: 100%"
              border
              stripe
              :default-expand-all="false"
              :header-row-class-name="'table-header'"
          >
            <el-table-column prop="orderNumber" label="订单号" width="180">
              <template #default="scope">
                <span class="order-number">{{ scope.row.orderNumber }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="courses.name" label="课程名称" width="250">
              <template #default="scope">
                <div class="course-info">
                  <img :src="scope.row.courses.image" :alt="scope.row.courses.name" class="course-thumbnail">
                  <span class="course-name">{{ scope.row.courses.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template #default="scope">
                <span class="amount">¥{{ scope.row.amount.toFixed(2) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="payMethod" label="支付方式" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.payMethod === 1 ? 'success' : 'primary'">
                  {{ scope.row.payMethod === 1 ? '微信支付' : '支付宝' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" width="160"/>
            <el-table-column prop="checkoutTime" label="支付时间" width="160"/>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button
                    v-if="scope.row.status === 0"
                    type="primary"
                    size="small"
                    @click="handlePay(scope.row)"
                >
                  去支付
                </el-button>
                <el-button
                    v-if="scope.row.status === 1"
                    type="success"
                    size="small"
                    @click="goToLearn(scope.row.courseId)"
                >
                  去学习
                </el-button>
                <el-button
                    v-if="scope.row.status === 1"
                    type="info"
                    size="small"
                    @click="handleRefund(scope.row)"
                >
                  申请退款
                </el-button>
                <el-button
                    type="text"
                    size="small"
                    @click="viewOrderDetail(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div v-if="orders.length === 0" class="empty-orders">
            <el-empty description="暂无订单"/>
            <el-button type="primary" @click="goToBrowseCourses">去选课</el-button>
          </div>

          <div class="pagination" v-if="orders.length > 0">
            <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                layout="prev, pager, next, jumper"
                :total="pagination.total"
                :page-sizes="[5, 10, 20]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="orderDetailVisible" title="订单详情" width="600px">
      <div v-if="selectedOrder" class="order-detail">
        <div class="detail-section">
          <h3>订单信息</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="订单号">{{ selectedOrder.orderNumber }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ selectedOrder.createTime }}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{ selectedOrder.checkoutTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{
                selectedOrder.payMethod === 1 ? '微信支付' : '支付宝'
              }}
            </el-descriptions-item>
            <el-descriptions-item label="订单状态">{{ getStatusText(selectedOrder.status) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="detail-section">
          <h3>课程信息</h3>
          <div class="course-detail">
            <img :src="selectedOrder.courseImage" :alt="selectedOrder.courseName" class="course-image">
            <div class="course-info">
              <h4>{{ selectedOrder.courseName }}</h4>
              <p class="course-price">¥{{ selectedOrder.amount.toFixed(2) }}</p>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="orderDetailVisible = false">关闭</el-button>
          <el-button v-if="selectedOrder && selectedOrder.status === 0" type="primary"
                     @click="handlePay(selectedOrder)">去支付</el-button>
          <el-button v-if="selectedOrder && selectedOrder.status === 1" type="success"
                     @click="goToLearn(selectedOrder.courseId)">去学习</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 页脚 -->
    <frontend-footer/>
  </div>
</template>

<script setup>
import FrontendHeader from '../../components/FrontendHeader.vue'
import FrontendFooter from '../../components/FrontendFooter.vue'
import {ref, reactive, computed, onMounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {User, VideoPlay, Document, Search} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {myOrdersQuery} from "@/api/Orders.js";

const route = useRoute()
const router = useRouter()

// 用户信息
const userInfo = reactive({
  id: '',
  username: '',
  name: '',
  avatar: 'https://picsum.photos/100/100?random=1'
})

// 订单数据
const orders = ref([])

// 筛选和搜索
const searchKeyword = ref('')
const filterStatus = ref('')
const dateRange = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total:0
})
//条件查询
const handleSearch=()=>{
  console.log("条件查询的值:------------")
  console.log(searchKeyword.value)
  console.log(dateRange.value)
  console.log("开始时间:",dateRange.value[0])
  console.log("结束时间:",dateRange.value[1])
  loadOrders()
}
// 订单详情
const orderDetailVisible = ref(false)
const selectedOrder = ref(null)

// 计算当前激活的菜单项
const activeMenu = computed(() => {
  return route.path
})

// 加载用户信息
const loadUserInfo = () => {
  // 这里应该调用API获取用户信息
  const storedUserInfo = sessionStorage.getItem('userInfo')
  if (storedUserInfo) {
    const parsedUserInfo = JSON.parse(storedUserInfo)
    Object.assign(userInfo, {
      ...parsedUserInfo,
      name: parsedUserInfo.name || parsedUserInfo.username
    })
  }
}

// 加载订单数据
const loadOrders = () => {
  //获取用户值
  const user = sessionStorage.getItem("userInfo");
  // 这里应该调用API获取用户订单
  myOrdersQuery({
    keyword:searchKeyword.value,
    status:filterStatus.value,
    curPage: pagination.currentPage,
    pageSize: pagination.pageSize,
    uid:JSON.parse(user).id,
    startTime:dateRange.value[0],
    endTime:dateRange.value[1]
  }).then(res => {
    console.log(res)
    //给分页信息赋值
    pagination.currentPage=res.data.curPage
    pagination.pageSize = res.data.pageSize
    pagination.total = res.data.total
    orders.value = res.data.dataList
  })
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '未支付'
    case 1:
      return '已支付'
    case 2:
      return '已退款'
    default:
      return '未知状态'
  }
}

// 获取状态类型（用于标签颜色）
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    case 2:
      return 'info'
    default:
      return 'default'
  }
}

// 去支付
const handlePay = (order) => {
  // 这里应该跳转到支付页面或调用支付API
  ElMessage.info('支付功能待实现')
}

// 去学习
const goToLearn = (courseId) => {
  router.push(`/course/learn/${courseId}`)
}

// 申请退款
const handleRefund = (order) => {
  ElMessageBox.confirm(
      '确定要申请退款吗？',
      '退款确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 这里应该调用退款API
    const index = orders.value.findIndex(o => o.id === order.id)
    if (index !== -1) {
      orders.value[index].status = 2
    }
    ElMessage.success('退款申请成功')
  }).catch(() => {
    // 取消操作
  })
}

// 查看订单详情
const viewOrderDetail = (order) => {
  selectedOrder.value = order
  orderDetailVisible.value = true
}

// 去浏览课程
const goToBrowseCourses = () => {
  router.push('/courses')
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadOrders()
}

// 处理当前页变化
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  loadOrders()
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  router.push(key)
}

// 页面加载时获取数据
// 页面加载时检查是否有支付成功的参数
onMounted(() => {
  loadUserInfo()
  loadOrders()

  // 检查URL参数是否有支付成功的标记
  if (route.query.success === 'true') {
    ElMessage.success('订单支付成功！')
    // 清除URL参数，避免刷新页面时再次显示消息
    router.replace({
      path: route.path,
      query: {}
    })
  }
})
</script>

<style scoped>
.user-orders-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding-top: 0;
  padding-bottom: 120px;
  position: relative;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 0;
  text-align: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 24px;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-header p {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;
}

.content-wrapper {
  display: flex;
  gap: 20px;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  margin-top: 20px;
}

.sidebar {
  width: 240px;
  flex-shrink: 0;
}

.user-info-card {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.avatar-container {
  margin-bottom: 12px;
}

.user-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.user-info-card h3 {
  font-size: 16px;
  margin-bottom: 6px;
  color: #303133;
  line-height: 1.4;
}

.user-stats {
  color: #606266;
  font-size: 12px;
  margin: 0;
}

.profile-menu {
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.profile-menu .el-menu-item {
  padding: 12px 20px;
  height: auto;
  line-height: 1.5;
}

.profile-menu .el-menu-item.is-active {
  color: #409eff;
  background-color: #ecf5ff;
}

.main-content {
  flex: 1;
  padding: 24px;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

.order-filters {
  background-color: white;
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-input {
  width: 300px;
}

.filter-select {
  width: 150px;
}

.date-picker {
  width: 300px;
}

.order-number {
  font-family: monospace;
  color: #667eea;
  font-size: 13px;
}

/* 表头样式优化 */
.table-header {
  background-color: #fafafa;
  font-weight: 600;
  font-size: 14px;
}

/* 操作按钮间距优化 */
.el-table .el-button + .el-button {
  margin-left: 8px;
}

.course-info {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.course-thumbnail {
  width: 60px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  flex-shrink: 0;
}

.course-name {
  flex: 1;
  white-space: normal;
  word-break: break-all;
  line-height: 1.4;
  max-height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.course-thumbnail {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

.amount {
  font-weight: bold;
  color: #f56c6c;
  font-size: 16px;
}

.empty-orders {
  background-color: white;
  border-radius: 8px;
  padding: 60px 20px;
  text-align: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.empty-orders .el-button {
  margin-top: 20px;
}

.pagination {
  margin-top: 30px;
  text-align: center;
}

/* 订单详情样式 */
.order-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
}

.course-detail {
  display: flex;
  gap: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.course-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.course-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.course-price {
  margin: 0;
  color: #f56c6c;
  font-size: 20px;
  font-weight: bold;
}

@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
  }

  .profile-menu {
    display: flex;
    justify-content: space-around;
  }

  .order-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input,
  .filter-select,
  .date-picker {
    width: 100%;
  }

  .course-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .course-detail {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
}
</style>